﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using WcfHost;
using System.ServiceProcess;
using NLog;

namespace WcfHost {

    class WcfHostApp {

        public static string ServiceName = string.Empty;
				private static Logger logger = LogManager.GetCurrentClassLogger(); 

        /// <summary>
        /// Direct all output to the console and log file
        /// </summary>
        /// <param name="msg">The MSG.</param>
        internal static void LogOutput(string msg) {
            Console.WriteLine(msg);
			try {
				logger.Info(msg);
			} catch (Exception) {
				// ignore - no where to store output
			}
			
        }

        /// <summary>
        /// Application entry point, if the command line argument "-C" is specified it will run as a console application, otherwise the app will run as a windows service.
        /// The windows service is installed by running // FIXME MIN
        /// The name of the windows service is read from configuration parameter "ServiceName" at the time of installation, 
        /// </summary>
        /// <param name="args">The arguments for the app, p.t. only "-C|-c" is in use.</param>
        static void Main(string[] args) {
            // load all services from the configuration file.
            if (args.Length > 0 && args[0].Trim().ToUpperInvariant() == "-C") {
                LogOutput("WCF Host Applikation, tryk [Enter] for at lukke");
                try {
                    // Start all services
                    ServiceWrapper wrapper = new ServiceWrapper();
                    wrapper.StartServices();

                    LogOutput("Hoster følgende services:");
                    LogOutput(Environment.NewLine);
                    LogOutput(wrapper.ToString());

                    WorkerWrapper workers = new WorkerWrapper();
                    workers.StartWorkerThreads();
                }
                catch (Exception e) {
                    // whoops, couldn't start, log the reason, in most cases it is proberly a configuration problem
                    LogOutput(e.Message);
                }
                Console.ReadLine();
            }
            else {
                // Run the service
                ServiceBase[] SerBase = new ServiceBase[] { new WcfHostService() };
                ServiceBase.Run(SerBase);
            }
        }
    }
}
